/* 
 * File:   Sum.cpp
 * Author: Gab'z
 * 
 * Created on 4 juin 2012, 23:20
 */

#include "Sum.h"
#include "../../literal/Integer.h"
#include "../../literal/Number.h"

namespace calculator {

    Sum::Sum(const std::string name) : NaryOperator(name) {
    }

    Sum::Sum(const Sum& orig) : NaryOperator(orig._name) {
    }

    Sum::~Sum() {
    }

    Sum* Sum::clone() const {
        return new Sum(_name);
    }

    const Number* Sum::apply(const Stack* stack) const throw (ArithmeticException) {
        //if (stack->size() == 0) throw CommandException("Empty stack");
        Number* resNumber = new Integer(0);
        for (unsigned int i = 0; i < stack->size(); i++) {
            const Number* loopStackNumber = dynamic_cast<const Number*> (stack->getConstant(i));
            if (loopStackNumber == 0) {
                std::ostringstream oss;
                oss << "NaN : " << ((stack->getConstant(i) != 0) ? stack->getConstant(i)->toString() : "EmptyStack");
                throw ArithmeticException(oss.str());
            }
            Number* loopResNumber;
            try {
                loopResNumber = add(resNumber, loopStackNumber);
            } catch (ArithmeticException& e) {
               // delete loopStackNumber;
                throw;
            }
            delete resNumber;
            resNumber = loopResNumber;
        }

        return resNumber;
    }
}